package fun.codedesign.yinxue.text.panel;

import org.yinxue.swing.core.standard.YxButton;
import org.yinxue.swing.core.standard.YxPanel;
import org.yinxue.swing.core.util.SwingUtils;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class ConfirmPanel extends YxPanel {

    public JTextField inputname;

    public YxButton cancelButton;
    public YxButton confirmButton;

    public JFrame jFrame;

    @Override
    public void init() {
        inputname = createTextField(10);
        confirmButton = createYxButton("确定", 80, 40);
        cancelButton = createYxButton("取消", 80, 40);
    }

    @Override
    public void position() {
        add(inputname, refreshPosition(0, 0, 2, 1, 1, 1, H));
        add(cancelButton, refreshPosition(0, 1, 1, 1, 1, 1, H));
        add(confirmButton, refreshPosition(1, 1, 1, 1, 1, 1, H));
    }

    @Override
    public void action() {
        cancelButton.addYxActionListener(e -> {
            hideFrame();
        });

        confirmButton.addYxActionListener(e -> {
            hideFrame();
        });
        inputname.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {

            }

            @Override
            public void keyPressed(KeyEvent e) {
                System.out.println(e.toString());
                if (e.getKeyCode() == 10) {
                    hideFrame();
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }
        });
    }

    private void hideFrame() {
        jFrame.setVisible(false);
    }

    public void doRun() {
        SwingUtilities.invokeLater(() -> {
            SwingUtils.initDefaultUI();
            try {
                JFrame jFrame = SwingUtils.ofJFrame("重命名文件", 300, 200);
                jFrame.add(this);
                this.jFrame = jFrame;
                jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                jFrame.setVisible(true);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    public static void main(String[] args) {
        new ConfirmPanel().doRun();
    }
}
